//
//  CardView.m
//  BeautyBaoUnion
//
//  Created by 肖智 on 2016/10/25.
//  Copyright © 2016年 肖智. All rights reserved.
//

#import "CardView.h"
#import "Animator.h"
#define MAXDISPLAYNUMBER 4
@interface CardItemView()
@property(nonatomic,strong)Animator *animator;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UIButton  *swithchButton;
@property(nonatomic,assign)NSInteger dataIndex;
@end
@implementation CardItemView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.imageView];
        [self addSubview:self.swithchButton];
//        self.layer.borderWidth = 1/[UIScreen mainScreen].scale;
//        self.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5].CGColor;
        self.backgroundColor = [UIColor colorWithHex:0xfaf7f2 alpha:1.0];
        self.layer.shadowOffset = CGSizeMake(0.0, 1.0);
        self.layer.shadowColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.7].CGColor;
        self.layer.shadowRadius = 1.0;
        self.layer.shadowOpacity = 0.2;
        self.multipleTouchEnabled = NO;
    }
    return self;
}
- (void)setAnimator:(Animator *)animator{
    _animator = animator;
    self.layer.transform = animator.transform;
}
- (void)setDataIndex:(NSInteger)dataIndex{
    _dataIndex = dataIndex;
    [self.swithchButton setTitle:[NSString stringWithFormat:@"%ld",_dataIndex] forState:UIControlStateNormal];
}
- (void)prepareForUse{
    self.layer.transform = CATransform3DIdentity;
    _dataIndex = -1;
}
- (UIImageView *)imageView{
    if(!_imageView){
        _imageView = [[UIImageView alloc] init];
        _imageView.frame = self.bounds;
        _imageView.image = [UIImage imageNamed:@"circle_bg"];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _imageView;
}
- (UIButton *)swithchButton{
    if(!_swithchButton){
        _swithchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _swithchButton.frame = self.bounds;
        
    }
    return _swithchButton;
}
- (void)dealloc{
    NSLog(@"CardItemView dealloc");
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
@interface CardView(){
    NSMutableArray *_animatorArray;
    NSMutableArray *_itemViewArray;
    NSMutableSet   *_reusableSet;
    NSMutableArray        *_dataSource;
    CardItemView   *_topItemView;
    CGPoint         _originCenter;
    CGPoint         _currentCenter;
    CGPoint        _lastPoint;
    CGPoint        _currentPoint;
    Animator       *_bigAnimator;
    NSInteger      _currentIndex;
    NSTimeInterval      _repeatDuration;
}
@property(nonatomic,assign)CGSize itemSize;
@property(nonatomic,assign)NSTimer *autoRunTimer;
@property(nonatomic,assign)BOOL     shouldRelease;
@end
@implementation CardView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _animatorArray = [[NSMutableArray alloc] initWithCapacity:0];
        _itemViewArray = [[NSMutableArray alloc] initWithCapacity:0];
        _dataSource = [[NSMutableArray alloc] initWithCapacity:0];
        _reusableSet = [[NSMutableSet alloc] initWithCapacity:0];
        _itemSize = CGSizeMake(frame.size.width, frame.size.height-20);
        [self genAnimator];
        self.backgroundColor = [[UIColor cyanColor] colorWithAlphaComponent:0.3];

        _bigAnimator = [[Animator alloc] init];
        CATransform3D transform = CATransform3DMakeScale(1.1, 1.02, 1.0);
        transform = CATransform3DTranslate(transform, 0, 5, 0);
        _bigAnimator.transform = transform;
        _repeatDuration = 5.0;
        _shouldRelease = NO;
    }
    return self;
}
- (CardItemView *)genItemView{
    CardItemView *itemView = nil;
    itemView = (CardItemView *)[_reusableSet anyObject];
    if (itemView){
        NSLog(@"重用成功！");
        [itemView prepareForUse];
        itemView.frame = CGRectMake(0, 0, self.itemSize.width, self.itemSize.height);
        [_reusableSet removeObject:itemView];
        
    }else{
        NSLog(@"重用失败,生成新对象");
        itemView = [[CardItemView alloc] initWithFrame:CGRectMake(0, 0, self.itemSize.width, self.itemSize.height)];
        UIPanGestureRecognizer *g = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGestureR:)];
        [itemView addGestureRecognizer:g];
        [itemView.swithchButton addTarget:self action:@selector(didSelectItemView) forControlEvents:UIControlEventTouchUpInside];
    }
    return itemView;
}
- (void)didSelectItemView{
    if (_itemViewArray.count==0) {
        return;
    }
    CardItemView *itemView = (CardItemView *)[_itemViewArray firstObject];
    if(itemView){
        NSLog(@"%@",_dataSource[itemView.dataIndex]);
    }
}
- (void)genAnimator{
    if (MAXDISPLAYNUMBER <= 0){
        return;
    }
    Animator *animator = nil;
    for(NSInteger i=0;i<MAXDISPLAYNUMBER;i++){
        animator = [[Animator alloc] init];
        animator.size = self.itemSize;
        animator.index = i;
        [_animatorArray addObject:animator];
    }
}
- (void)layoutItemWithData:(NSArray *)dataSource{
    //移除原有的itemview并添加到重用集合
    for(CardItemView *aview in _itemViewArray){
        if(aview){
            [aview removeFromSuperview];
            [_reusableSet addObject:aview];
        }
    }
    [_itemViewArray removeAllObjects];
    [_dataSource removeAllObjects];
    if(!dataSource||dataSource.count==0){
        return;
    }
    [_dataSource addObjectsFromArray:dataSource];
    CardItemView *itemView;
    NSInteger maxCount = _dataSource.count>MAXDISPLAYNUMBER?MAXDISPLAYNUMBER:_dataSource.count;
    _currentIndex = maxCount-1;
    for(NSInteger i=0;i<maxCount;i++){
        itemView = [self genItemView];
        Animator *animator = (Animator *)_animatorArray[i];
        itemView.dataIndex = i;
        itemView.animator = animator;
        itemView.userInteractionEnabled = (i==0);
        [_itemViewArray addObject:itemView];
        [self.layer insertSublayer:itemView.layer atIndex:0];
    }
    
}
- (void)showNext{
    CardItemView *itemView;
    Animator *animator;
    [self inserItemView];
    for(NSInteger i=0;i<_itemViewArray.count;i++){
        itemView = (CardItemView *)_itemViewArray[i];
        animator = (Animator *)_animatorArray[i];
        itemView.userInteractionEnabled = NO;
        if(i==0){
            [UIView animateWithDuration:0.5 animations:^{
                itemView.animator = _bigAnimator;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 animations:^{
                    itemView.animator = animator;
                } completion:^(BOOL finished) {
                    self.userInteractionEnabled = YES;
                    itemView.userInteractionEnabled = YES;
                    if(self.autoRunTimer==nil&&!self.shouldRelease){
                        [self startAutoRun];
                    }
                }];
            }];
        }else if(_itemViewArray.count==3&&i == _itemViewArray.count-1){
            [UIView animateWithDuration:0.3 animations:^{
                itemView.alpha = 0.7;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.3 animations:^{
                    itemView.alpha = 1.0;
                } completion:^(BOOL finished) {
                    
                }];
            }];
        }else if(_itemViewArray.count>=4&&i>=_itemViewArray.count-2){
            itemView.animator = animator;
            [UIView animateWithDuration:0.3 animations:^{
                itemView.alpha = 0.7;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.3 animations:^{
                    itemView.alpha = 1.0;
                } completion:^(BOOL finished) {
                    
                }];
            }];
        }
        else{
            itemView.animator = animator;
        }
    }
}
- (NSInteger)getNextIndex{
    _currentIndex++;
    if (_currentIndex>=_dataSource.count) {
        _currentIndex = 0;
    }
    return _currentIndex;
}
- (void)inserItemView{
    CardItemView *itemView = [self genItemView];
    Animator *animator = (Animator *)_animatorArray[_itemViewArray.count];
    itemView.animator = animator;
    itemView.dataIndex = [self getNextIndex];
    [_itemViewArray addObject:itemView];
    [self.layer insertSublayer:itemView.layer atIndex:0];
}
- (void)startAutoRun{
    self.autoRunTimer = [NSTimer scheduledTimerWithTimeInterval:_repeatDuration target:self selector:@selector(autoRunNext:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.autoRunTimer forMode:NSRunLoopCommonModes];
}
- (void)stopAutoRun{
    if(self.autoRunTimer){
        [self.autoRunTimer invalidate];
        self.autoRunTimer = nil;
    }
}
- (void)autoRunNext:(NSTimer *)timer{
    _topItemView = (CardItemView *)[_itemViewArray firstObject];
    _originCenter = _topItemView.center;
    self.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.7 animations:^{
        _topItemView.center = CGPointMake(_originCenter.x, -_originCenter.y);
    } completion:^(BOOL finished) {
        [_topItemView removeFromSuperview];
        [_reusableSet addObject:_topItemView];
        [_itemViewArray removeObject:_topItemView];
        [self showNext];
    }];
}
- (void)handleGestureR:(UIGestureRecognizer *)g{
    //少于两个不作处理
    if(_itemViewArray.count<2){
        return;
    }
    switch (g.state) {
        case UIGestureRecognizerStateBegan:
            [self stopAutoRun];
            _topItemView = (CardItemView *)[_itemViewArray firstObject];
            _lastPoint = [g locationInView:self];
            _originCenter = _topItemView.center;
            break;
        case UIGestureRecognizerStateChanged:
            _currentPoint = [g locationInView:self];
            CGFloat deltY = _currentPoint.y-_lastPoint.y;
            _topItemView.center = CGPointMake(_topItemView.center.x, _topItemView.center.y+deltY);
            if(_topItemView.center.y>_originCenter.y){
                _topItemView.center = _originCenter;
            }
            _lastPoint = _currentPoint;
            break;
        case UIGestureRecognizerStateEnded:
            if(_topItemView.center.y>0){
                self.userInteractionEnabled = NO;
                [UIView animateWithDuration:0.4 animations:^{
                    _topItemView.center = _originCenter;
                } completion:^(BOOL finished) {
                    self.userInteractionEnabled = YES;
                }];
            }else{
                self.userInteractionEnabled = NO;
                [UIView animateWithDuration:0.4 animations:^{
                    _topItemView.center = CGPointMake(_originCenter.x, -_originCenter.y);
                } completion:^(BOOL finished) {
                    [_topItemView removeFromSuperview];
                    [_reusableSet addObject:_topItemView];
                    [_itemViewArray removeObject:_topItemView];
                    [self showNext];
                }];
            }
            break;
        case UIGestureRecognizerStateCancelled:
            if(_topItemView.center.y>0){
                self.userInteractionEnabled = NO;
                [UIView animateWithDuration:0.4 animations:^{
                    _topItemView.center = _originCenter;
                } completion:^(BOOL finished) {
                    self.userInteractionEnabled = YES;
                }];
            }else{
                self.userInteractionEnabled = NO;
                [UIView animateWithDuration:0.4 animations:^{
                    _topItemView.center = CGPointMake(_originCenter.x, -_originCenter.y);
                } completion:^(BOOL finished) {
                    [_topItemView removeFromSuperview];
                    [_reusableSet addObject:_topItemView];
                    [_itemViewArray removeObject:_topItemView];
                    [self showNext];
                }];
            }
            break;
            
        default:
            break;
    }
}
- (void)willDealloc{
    self.shouldRelease = YES;
    [self stopAutoRun];
}
- (void)dealloc{
    [self stopAutoRun];
    NSLog(@"CardView dealloc");
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
